package org.queueify.servlet;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.queueify.QueueifyException;
import org.queueify.QueueifyPushQueueTask;
import org.queueify.QueueifyService;
import org.queueify.QueueifySingletonTask;


public class QueueifyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	final static private Logger logger = Logger.getLogger(QueueifyServlet.class.getSimpleName());
	
	final static private long MAX_PROCESS_TIME_SECONDS = 11 * 60; // we only have 10 minutes for execution. eleven should
	// put our lease beyond that so that if a lock is not surrendered properly, we can recover it after 11 minutes and
	// know that the process is not still running.

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		try {
			QueueifyPushQueueTask task = QueueifyService.reconstructPushQueueTask(req);
			if ( task instanceof QueueifySingletonTask ) {
				try {
					String className = task.getClass().getName();
					QueueifySingletonMutex.leaseLock(className, MAX_PROCESS_TIME_SECONDS);
					task.doTask(req, resp);
					QueueifySingletonMutex.surrenderLock(className);
				}
				catch (QueueifyAlreadyLockedException e) {
					// a lock already exists. run nothing.
					logger.info("QueueifySingletonMutex lock already exists for "+task.getClass().getName());
				}
			} else {
				task.doTask(req, resp);
			}
		}
		catch (QueueifyException e) {
			logger.severe(e.getMessage());
			// But don't return an error -- we don't want to requeue this kind of error since it will just happen again.
			// This error has to do with the reconstruction of the Task.
		}
	}

}
